﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommunity.Members;
using XCommunity.Data;

namespace XCommunity.Web
{
  public class WebAccountService : AccountService
  {
    private WebCommunityContext _communityContext;

    public WebAccountService( WebCommunityContext context )
    {
      _communityContext = context;
    }

    public void Init()
    {
      _accountCache = new AccountCache();
      _accountCache.Init( ( (ICommunityContext) _communityContext ).CacheService );

    }

    private AccountCache _accountCache;

    internal AccountCache AccountCache
    {
      get { return _accountCache; }
    }

    /// <summary>
    /// 获取当前登录的用户列表
    /// </summary>
    public override IEnumerable<string> LoggedAccounts
    {
      get { return AccountCache.LoggedAccounts; }
    }

    /// <summary>
    /// 获取登录用户上次活动时间
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    public override DateTime GetLastActivityTime( string username )
    {
      return DateTime.MinValue;
    }


    /// <summary>
    /// 判断一个用户名是否可以用于注册
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns>验证结果</returns>
    public bool CanRegister( string username )
    {
      if ( !IsValidUsername( username ) )
        return false;

      return !IsRegistered( username );
    }

    /// <summary>
    /// 判断一个用户名是否已经被注册
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    public bool IsRegistered( string username )
    {
      return ( AccountDataProvider.GetUsername( username ) != null );
    }

    /// <summary>
    /// 尝试注册一个用户帐户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <returns></returns>
    public bool Register( string username, string password )
    {
      return AccountDataProvider.CreateAccount( username, AccountCrypto.ComputePasswordHash( password ) );
    }


    internal Account GetAccount( string token )
    {
      var account = AccountCache.GetAccount( token );

      if ( account == null )
      {

        if ( token.EndsWith( "%" ) )
          return null;

        account = AccountManage.CreateAccount( token );
        if ( account != null )
          AddAccount( account );
      }

      return account;
    }

    internal void AddAccount( Account account )
    {
      AccountCache.AddAccount( account.Token, account );
    }

    internal bool IsValidUsername( string username )
    {
      return NameRegex.IsMatch( username );
    }

  }
}
